package com.huatai.exchange.integration.base.impl;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.CloseUtils;
import com.faneui.integration.http.HttpClientUtils;
import com.google.common.collect.Maps;
import com.huatai.base.facade.bean.file.UploadFileResp;
import com.huatai.base.facade.bean.file.ZipFilesResp;
import com.huatai.exchange.integration.base.AbstractBaseService;
import com.huatai.exchange.integration.base.service.FileOperateService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Service
public class FileOperateServiceImpl extends AbstractBaseService implements FileOperateService {

	@Override
	public String uploadFile(File... files) throws BusinessException {
		String url = baseUrl + "file/upload";
		UploadFileResp resp = HttpClientUtils.uploadFile(url, UploadFileResp.class, files);
		return resp.getFilePath();
	}

	@Override
	public String uploadFile(InputStream... iss) throws BusinessException {
		String url = baseUrl + "file/upload";
		UploadFileResp resp = HttpClientUtils.uploadFile(url, UploadFileResp.class, iss);
		return resp.getFilePath();
	}

	@Override
	public void downloadFile(OutputStream os, String fileRealPath) throws BusinessException {
		String url = baseUrl + "file/download";
		Map<String, Object> param = Maps.newHashMap();
		param.put("fileName", fileRealPath);
		HttpClientUtils.downLoadFile(url, param, os);
	}

	@Override
	public void downloadFile(File file, String fileRealPath) throws BusinessException {
		OutputStream os = null;
		try{
			os = new FileOutputStream(file) ;
			downloadFile(os,fileRealPath);
		}catch (Exception ex) {
			BusinessException.throwBusinessException(ex);
		}finally {
			CloseUtils.safeClose(os);
		}
	}

	@Override
	public String uploadZipFiles(String filePaths ,String fileNames) throws BusinessException {
		return uploadZipFiles(filePaths,fileNames,null);
	}

	@Override
	public String uploadZipFiles(String filePaths, String fileNames, String isHaveZipFile) throws BusinessException {
		String url = baseUrl + "/file/zipfile" ;
		Map<String,Object> resvMap = Maps.newHashMap() ;
		resvMap.put("filePaths",filePaths) ;
		resvMap.put("fileNames",fileNames) ;
		if(StringUtils.isNotBlank(isHaveZipFile))
			resvMap.put("isHaveZipFile",isHaveZipFile) ;
		return HttpClientUtils.get(url,resvMap, ZipFilesResp.class).getZipFileName();
	}
}
